package com.company.netty2;

import com.company.serialization.Student;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @description:
 * @author: ruoan
 * @date: 2021/1/1 17:24
 */
public class EchoClientHandlerWithEncoderAndDecoder extends ChannelInboundHandlerAdapter {

    private final int number ;

    public EchoClientHandlerWithEncoderAndDecoder(int number) {
        this.number = number;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Student[] students = getStudentInfos();
        for (Student s:students) {
            ctx.write(s);
        }
        ctx.flush();
    }

    private Student[] getStudentInfos() {
        Student[] students = new Student[number];
        for (int i = 0; i < number; i++) {
            Student s = new Student();
            s.setUserId(i);
            s.setUserName("abdc--->"+i);
            students[i] = s;
        }
        return students;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("收到消息："+msg);
        ctx.write(msg);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        ctx.close();
        System.out.println("关闭");
    }
}
